package com.android.activity.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.R;
import com.android.activity.HomePageActivity;
import com.android.bean.Good;
import com.android.bean.ImageBean;
import com.android.bean.ResponseData;
import com.android.bean.User;
import com.android.databinding.FragmentPublishPageBinding;
import com.android.model.upload.UpListener;
import com.android.model.upload.UpModelimpl;
import com.android.utils.FileUtil;
import com.android.utils.GlideEngine;
import com.android.utils.ToastUtil;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
import top.zibin.luban.OnNewCompressListener;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class PublishProductFragment extends Fragment implements View.OnClickListener, UpListener {
    private FragmentPublishPageBinding binding;
    private UpModelimpl upModelimpl;
    private List<MultipartBody.Part> fileArrayList;
    private ImageBean imageBean;
    private Good goods;
    private User user;

    public PublishProductFragment() {
        // Required empty public constructor
    }


    public static PublishProductFragment newInstance() {
        PublishProductFragment fragment = new PublishProductFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

        upModelimpl = new UpModelimpl();
        if (getArguments() != null) {
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    //通过Eventbus获取用户
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void getUser(ResponseData<User> responseData){
        this.user = responseData.getData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentPublishPageBinding.inflate(inflater, container, false);
        View view = binding.getRoot();

        binding.btnRelease.setOnClickListener(this);
        binding.btnAddImage.setOnClickListener(this);
//        binding.

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_release:
                Log.e("1","发布按钮点击");
                publishGoods();

                break;
            case R.id.btn_add_image:
                getPicture();
                break;


        }
    }

    //发布商品
    private void publishGoods() {
        goods = new Good();

        goods.setAddr(binding.etAddr.getText().toString());
        goods.setContent(binding.etContent.getText().toString());
        if (imageBean == null){
            ToastUtil.showMsg(getActivity(),"请先上传图片");
            return;
        }else {
            Log.e("1",imageBean.getImageCode().toString());
            ToastUtil.showMsg(getActivity(),"上传图片成功");
        }

        goods.setImageCode(imageBean.getImageCode());
        goods.setPrice(Integer.parseInt(binding.etPrice.getText().toString()));
        goods.setTypeId(Integer.parseInt(binding.etGoodsType.getText().toString()));
        goods.setTypeName(binding.etGoodsTypeName.getText().toString());
        goods.setUserId(user.getId());

        upModelimpl.addGoods(goods,this);

    }

    //获取相册图片
    public void getPicture(){
        PictureSelector.create(getActivity())
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .isOriginalControl(true)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        fileArrayList = new ArrayList<>();
                        for (int i = 0; i < result.size(); i++) {
                            String imgPath = result.get(i).getRealPath();
                            File file = new File(imgPath);

                            //参数添加
                            MultipartBody.Builder builder =
                                    new MultipartBody.Builder()
                                            .setType(MultipartBody.FORM);

                            RequestBody requestFile =
                                    RequestBody.create(MediaType.parse("image/png"), file);//文件形式

                            builder.addFormDataPart("fileList", file.getName(), requestFile);
                            fileArrayList = builder.build().parts();
                        }
                        updateImage(fileArrayList);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    //上传
    private void updateImage(List<MultipartBody.Part> parts) {
        upModelimpl.UpImage(parts,this);
    }

    @Override
    public void upImageOnSuccess(ResponseData<ImageBean> responseData) {
        ImageBean data = responseData.getData();
        if(data == null) {
            Log.e("unconnect", "can not get response data!!");
            return ;
        }

        imageBean = data;
        Log.e("str",String.valueOf(imageBean.getImageCode()));
    }

    @Override
    public void addGoodsOnSuccess(ResponseData<Good> responseData) {
        Good data = responseData.getData();
        if(data == null) {
            Log.e("unconnect", "can not get response data!!");
            return ;
        }

        this.goods = data;
        if (responseData.getCode() == 200){
//            ToastUtil.showMsg(getActivity(),"发布成功,即将跳转页面");
            Intent intent = new Intent(getActivity(), HomePageActivity.class);
            startActivity(intent);
        }
    }
}